/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}


var list1 = {
    val: 9,
    next: {
        val: 9,
        next: {
            val: 9,
            next: {
                val: 9,
                next: {
                    val: 9,
                    next: {
                        val: 9,
                        next: null
                    }
                }
            }
        }
    }
}
var list2 = {
    val: 9,
    next: {
        val: 9,
        next: {
            val: 9,
            next: {
                val: 9,
                next: null
            }
        }
    }
}



var addTwoNumbers = function (l1, l2) {
    let flag = 0
    let p1 = l1, p2 = l2;
    for (; ;) {
        p1 = p1.next;
        p2 = p2.next;
        if (p1 == null) {
            flag = 1;
            break;
        }
        if (p2 == null) {
            flag = 2;
            break;
        }
    }
    let add_l = flag == 1 ? l1 : l2
    let ans_l = flag == 1 ? l2 : l1
    while (add_l != null || ans_l != null) {
        if(add_l != null){
            var sum = add_l.val + ans_l.val;
            if (sum < 10) ans_l.val = sum;
            else {
                ans_l.val = sum % 10;
                if (ans_l.next == null) ans_l.next = {val:0,next:null}
                ans_l.next.val += parseInt((sum / 10));
            }
            ans_l = ans_l.next
            add_l = add_l.next
        }
        else{
            if(ans_l.val<10) break;
            else{
                if (ans_l.next == null) ans_l.next = {val:0,next:null}
                ans_l.next.val += parseInt((ans_l.val / 10));
                ans_l.val %=   10;
                ans_l = ans_l.next
            }
        }
    }
    debugger
    return flag == 1 ? l2 : l1;
};

console.log(addTwoNumbers(list1, list2))

// console.log(list1.val + list2.val)
